﻿using System;
using System.Collections.Generic;
using System.IO;
using Best.SmartCms.Dto.Common;
using Best.SmartCms.Dto.Response;
using Best.SmartCms.Service.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace Best.SmartCms.API.Controllers
{
    /// <summary>
    /// 文件
    /// </summary>
    public class FileController : Controller
    {
       
        private readonly WorkContext _workContext;
        private readonly FileService _fileService;
        private readonly IHostingEnvironment _hostingEnvironment;

        /// <summary>
        ///  构造函数
        /// </summary>
        /// <param name="workContext"></param>
        /// <param name="fileService"></param>
        /// <param name="hostingEnvironment"></param>
        public FileController(WorkContext workContext, FileService fileService, IHostingEnvironment hostingEnvironment)
        {
            _workContext = workContext;
            _fileService = fileService;
            _hostingEnvironment = hostingEnvironment;
        }


        /// <summary>
        /// CkEditor 编辑器图片上传 本地路径
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("file/UploadCkEditorImage")]
        public JsonResult UploadCkEditorImage()
        {
            var files = Request.Form.Files;
            if (files.Count == 0)
            {
                var rError = new
                {
                    uploaded = false,
                    url = string.Empty
                };
                return Json(rError);
            }
            var formFile = files[0];
            var upFileName = formFile.FileName;
            //大小，格式校验....
            var fileName = DateTime.Now.ToFileTime() + Path.GetExtension(upFileName);
            string webRootPath = _hostingEnvironment.WebRootPath;
            string saveDir = Path.Combine(webRootPath, "upload");
            string savePath = Path.Combine(saveDir, fileName);
            var previewPath = "/files/upload/" + fileName;

            bool result = true;
            try
            {
                if (!Directory.Exists(saveDir))
                {
                    Directory.CreateDirectory(saveDir);
                }
                using (FileStream fs = System.IO.File.Create(savePath))
                {
                    formFile.CopyTo(fs);
                    fs.Flush();
                }
            }
            catch (Exception ex)
            {
                result = false;
            }

            var rUpload = new
            {
                uploaded = result,
                url = result ? previewPath : string.Empty
            };

            return Json(rUpload);
        }

        /// <summary>
        /// 图片上传 本地路径
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("file/ImageUpaload")]
        public ApiResponse<UploadFileDto> ImageUpaload()
        {
            var files = Request.Form.Files;
            if (files.Count == 0)
            {
                return ApiResponse<UploadFileDto>.Fails("请至少选择一张图片",ResponseCode.Forbidden);
            }

            var formFile = files[0];
            var upFileName = formFile.FileName;
            var fileExt = Path.GetExtension(upFileName);
            //大小，格式校验....
            var fileName = DateTime.Now.ToFileTime() + fileExt;
            string webRootPath = _hostingEnvironment.WebRootPath;
            string saveDir = Path.Combine(webRootPath, "upload");
            string savePath = Path.Combine(saveDir, fileName);
            var previewPath = "/files/upload/" + fileName;
            try
            {
                if (!Directory.Exists(saveDir))
                {
                    Directory.CreateDirectory(saveDir);
                }
                using (FileStream fs = System.IO.File.Create(savePath))
                {
                    formFile.CopyTo(fs);
                    fs.Flush();
                }
            }
            catch (Exception ex)
            {
                return ApiResponse<UploadFileDto>.Fails(ex.Message, ResponseCode.SystemError);
            }

            var result = new UploadFileDto
            {
                Type = fileExt,
                //Size = formFile.Length,
                Name = upFileName,
                Url = previewPath
            };

            return ApiResponse<UploadFileDto>.Succeeds(result);
        }

        /// <summary>
        /// 单个文件上传oss
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("files/uploadimage")]
        public ApiResponse<UploadFileDto> Uploadimage()
        {
            var res = new ApiResponse<UploadFileDto>();
            var httpFileCollection = Request.Form.Files;
            if (httpFileCollection.Count != 1)
            {
                res.Success = false;
                res.Message = "请选择一个文件上传！";
                res.Code = ResponseCode.ParameterError;
            }

            var fileParam = httpFileCollection[0];
            var fileName = fileParam.FileName;
            if (fileParam.Length > 0)
            {
                //后缀名
                var fileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1,
                    (fileName.Length - fileName.LastIndexOf(".", StringComparison.Ordinal) - 1));
                using (var stream = new MemoryStream())
                {
                    fileParam.CopyTo(stream);
                    stream.Position = 0;
                    var fileSize = stream.Length;
                    byte[] bytes = new byte[stream.Length];
                    stream.Read(bytes, 0, bytes.Length);
                    stream.Seek(0, SeekOrigin.Begin);
                    var ossKey = Guid.NewGuid().ToString();
                    var ret = _fileService.UploadImageByByte(bytes, ossKey, fileSize, fileName, fileExt);
                    res.Data = ret;
                    res.Success = true;
                    res.Message = "上传成功！";
                    res.Code = ResponseCode.Success;
                }

            }
            return res;
        }

        /// <summary>
        /// 批量上传图片oss
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("files/multiuploadimage")]
        public ApiResponse<List<UploadFileDto>> MultiUploadimage()
        {
            var res = new ApiResponse<List<UploadFileDto>>
            {
                Data = new List<UploadFileDto>()
            };
            var httpFileCollection = Request.Form.Files;
            if (httpFileCollection.Count == 0)
            {
                res.Success = false;
                res.Message = "要上传的文件不存在！";
                res.Code = ResponseCode.ParameterError;
            }

            foreach (var fileParam in httpFileCollection)
            {
                var fileName = fileParam.FileName;
                if (fileParam.Length > 0)
                {
                    //后缀名
                    var fileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1,
                        (fileName.Length - fileName.LastIndexOf(".", StringComparison.Ordinal) - 1));
                    using (var stream = new MemoryStream())
                    {
                        fileParam.CopyTo(stream);
                        stream.Position = 0;
                        var fileSize = stream.Length;
                        byte[] bytes = new byte[stream.Length];
                        stream.Read(bytes, 0, bytes.Length);
                        stream.Seek(0, SeekOrigin.Begin);
                        var ossKey = Guid.NewGuid().ToString();
                        var uploadRet = _fileService.UploadImageByByte(bytes, ossKey, fileSize, fileName, fileExt);
                        res.Data.Add(uploadRet);
                    }
                }
            }
            res.Success = true;
            res.Message = "上传成功！";
            res.Code = ResponseCode.Success;
            return res;
        }

       
       


    }
}
